import requests
from lxml import etree
import xml.etree.ElementTree as ET
from flask import Flask, render_template, request


def get_mobile(phone):
    url = f'https://www.ip138.com/mobile.asp?mobile={phone}&action=mobile'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36'}
    res = requests.post(url, headers=headers)
    res.encoding = 'utf-8'
    e = etree.HTML(res.text)
    dataList = []
    fieldList = e.xpath('//tbody/tr/td[1]/text()')
    eleList = e.xpath('//tbody/tr/td[2]')
    for i in range(len(fieldList)):
        ele = eleList[i]
        e2 = etree.fromstring(ET.tostring(ele))
        dataList.append({
            'name': fieldList[i],
            'value': e2.xpath('//span[1] /text() | //a[1] /text()')
        })
    return dataList


app = Flask(__name__)


@app.route('/')
def index():
    return render_template('search_phone_index.html')


@app.route('/search_phone')
def search():
    phone = request.args.get('phone')
    return get_mobile(phone)


app.run()
